package com.alex.controller;


import com.alex.ChatEntity.ChatCompletionChunk;
import com.alex.ChatEntity.Choice;
import com.alex.ChatEntity.MsgEntity;
import com.alibaba.fastjson.JSONObject;
import common.util.StringUtil;
import okhttp3.*;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Chat {
    public static void main(String[] args) {
        String send = send("黄瓜有益于身体健康");
        System.out.println(send);
    }

    public static String send(String question) {
        List<MsgEntity> msgEntities = new ArrayList<>();

        msgEntities.add(new MsgEntity("system", "请依据所给出的观点或陈述,提取其中核心的词语或者找出相似的词语,生成可以用来检索的词组,词组中间用空格隔开,不要输出多余的内容"));
        msgEntities.add(new MsgEntity("user", question));

        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(100, java.util.concurrent.TimeUnit.SECONDS)
                .readTimeout(1000, java.util.concurrent.TimeUnit.SECONDS)
                .writeTimeout(1000, java.util.concurrent.TimeUnit.SECONDS)
                .build();
        Request request = sendMsg(msgEntities);

        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {

            e.printStackTrace(System.err);
        }
        StringBuilder stringBuilder = new StringBuilder();
        if (null != response) {
            ResponseBody responseBody = response.body();
            if (null != responseBody) {
                InputStream inputStream = responseBody.byteStream();
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if ("[DONE]".equals(line) || "data: [DONE]".equals(line)) {
                            break;
                        }
                        line = line.replaceAll("data: ", "").trim();
                        try {
                            if (StringUtil.isNotNull(line)) {
                                ChatCompletionChunk chatCompletionChunk = JSONObject.parseObject(line, ChatCompletionChunk.class);
                                List<Choice> choices = chatCompletionChunk.getChoices();
                                for (Choice choice : choices) {
                                    String content = choice.getDelta().getContent().replaceAll("\n\n", "\n");
                                    stringBuilder.append(content);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace(System.err);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace(System.err);
                }
            }
        }
        return stringBuilder.toString();
    }

    public static Request sendMsg(List<MsgEntity> msgEntities) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("messages", JSONObject.toJSONString(msgEntities));
        map.put("model", "\"qwen-plus-latest\"");
        map.put("frequency_penalty", 0);
        map.put("max_tokens", 2000);
        map.put("presence_penalty", 0);
        map.put("stop", null);
        map.put("stream", true);
        map.put("temperature", 1);
        map.put("top_p", 0.9);
        String string = mapToString(map);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, string);
        Request request = new Request.Builder().url("https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer sk-c65ee8baf0c440238e51f74495107da3")
                .build();
        return request;
    }

    public static String mapToString(Map<String, Object> map) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("{");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (stringBuilder.length() > 1) { // 避免第一个元素前出现逗号
                stringBuilder.append(",");
            }
            String key = entry.getKey();
            Object value = entry.getValue();

            stringBuilder.append("\"").append(key).append("\":").append(value);

        }
        stringBuilder.append("}");
        return stringBuilder.toString();
    }

}
